package persistencia;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import dominio.PersistentObject;

	public abstract class DataAccessObject {

		private static Connection conn;

		protected static Connection getConnection() throws PersistentException {
			try {
				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
				String db = "jdbc:odbc:Taller";
				conn =DriverManager.getConnection(db, "", "");
				conn.setAutoCommit(false);
				return conn;
			}
			catch(SQLException sqex) {
				throw new PersistentException(sqex.getMessage());
			} catch (ClassNotFoundException e) {
				throw new PersistentException(e.getMessage());
			}
		}

		protected void commitTransaction() throws PersistentException {
			try {
				if(conn != null) conn.commit(); 
			}
			catch(SQLException sqex) {
				throw new PersistentException(sqex.getMessage());
			}
		}

		protected void rollBackTransaction() throws PersistentException{
			try {
				if(conn != null) conn.rollback(); 
			}
			catch(SQLException sqex) {
				throw new PersistentException(sqex.getMessage());
			}
		}

		protected static void closeConection() throws PersistentException {
			try {
				if(conn != null) conn.close();
			}
			catch(SQLException sqex) {
				throw new PersistentException(sqex.getMessage());
			}
		}
		
		public abstract void insert(PersistentObject obj) throws PersistentException;
		
		public abstract void update(PersistentObject obj) throws PersistentException;
		
		public abstract void delete(PersistentObject obj) throws PersistentException;
		
		public abstract List<Object> selectAll() throws PersistentException;
		
		public static int proximoOid() throws PersistentException{
		        int oid = -1;
		        try {
		        	conn=getConnection();
		        	conn.setAutoCommit(true);
		        	ResultSet rs = null;
		            String sql = "SELECT valor FROM Sistema WHERE nombre='UltimoId'";
		            Statement st = conn.createStatement();
		            rs = st.executeQuery(sql);
		            while (rs.next()) {
		                oid = rs.getInt("valor");
		            }
		            rs.close();
		            oid++;
		            st = conn.createStatement();
		            st.executeUpdate("UPDATE Sistema set valor=" + oid + " WHERE nombre='UltimoId'");
		            st.close();
		        } catch (SQLException e) {
		            throw new PersistentException(e.getMessage());
		        }
		        return oid;
		    }

	}
